package logic

import (
	"context"
	"crypto/md5"
	"time"

	"github.com/anaskhan96/go-password-encoder"
	_ "github.com/anaskhan96/go-password-encoder"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"user/internal/svc"
	"user/public"
	"user/user"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *UserRegisterLogic) UserRegister(in *user.UserRegisterRequest) (*user.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	if in.UserName == "" {
		return nil, status.Error(codes.FailedPrecondition, "UserName  is required")
	}

	if in.UserMobile == "" {
		return nil, status.Error(codes.FailedPrecondition, "UserMobile is required")
	}

	if in.UserPassword == "" {
		return nil, status.Error(codes.FailedPrecondition, "UserPassword is required")
	}

	//盐值加密
	options := &password.Options{10, 10000, 50, md5.New}
	salt, encodedPwd := password.Encode(in.UserPassword, options)

	//实例化用户信息
	info := public.User{
		UserMobile:       in.UserMobile,
		UserPassword:     in.UserPassword,
		UserName:         in.UserName,
		Salt:             salt,
		UserSaltPassword: encodedPwd,
		AddTime:          time.Now().Format("2006-01-02 15:04:05"),
	}
	//添加数据
	err := public.DB.Table("user").Create(&info).Error
	if err != nil {
		return nil, status.Error(codes.FailedPrecondition, "create user error "+err.Error())
	}

	return &user.UserRegisterResponse{
		Data: &user.UserInfo{
			UserId:     info.UserID,
			UserName:   info.UserName,
			UserMobile: info.UserMobile,
		},
	}, nil
}
